#!/bin/bash
#清除maven缓存
#rm -rf /root/local/mvnsource/*
#mvn clean package -DskipTests docker:build
#如果有存在的容器，先删除docker容器
dockerId=$(docker ps --filter name=iweibomonitor -q)
if [[ -n ${dockerId} ]]
then
  echo "****************start clean docker:[${dockerId}]****************"
  #先停止容器，否则无法删除
  docker stop ${dockerId}
  #删除容器
  docker rm ${dockerId}
else
  echo "****************not need clean docker:[${dockerId}]****************"
fi
#清除docker缓存
dockerimgs=$(docker images | grep monitor | awk -F ' ' '{print $3}' | grep -v IMAGE)
if [[ -n ${dockerimgs} ]]
then
  echo "****************start clean dockerimgs:[${dockerimgs}]****************"
  docker images | grep monitor | awk -F ' '  '{print $3}' | grep -v IMAGE | xargs docker rmi
else
  echo "****************not need clean dockerimgs:[${dockerimgs}]****************"
fi
#使用mvn命令构建docker镜像
/root/local/maven/bin/mvn clean package -DskipTests
#删除镜像tar缓存
imgTarPkg=${WORKSPACE}/monitor-docker-install.tar
if [ -f "$imgTarPkg" ]; then
  echo "****************start clean tar cache****************"
  rm -rf ${WORKSPACE}/monitor-docker-install.tar
else
  echo "****************not need clean tar cache****************"
fi
#生成docker镜像文件
docker save -o ${WORKSPACE}/monitor-docker-install.tar registry.cn-hangzhou.aliyuncs.com/edge-wy-demo/monitor:0.0.1-SNAPSHOT
#创建目录
monitorConfPath=/root/local/application/monitor/conf
if [ -d "$monitorConfPath" ]; then
  rm -rf /root/local/application/monitor/conf/*
else
  mkdir -p /root/local/application/monitor/conf
fi
#准备配置文件
cp -rf ${WORKSPACE}/src/main/resources/application.yml /root/local/application/monitor/conf/application.yml
ls -l /root/local/application/monitor/conf
#运行容器
echo "****************start run docker****************"
docker run -itd --name iweibomonitor -p 32951:32951 -v /root/local/application/monitor/conf:/app/config --restart=always registry.cn-hangzhou.aliyuncs.com/edge-wy-demo/monitor:0.0.1-SNAPSHOT /bin/bash
sleep 10
newDockerId=$(docker ps --filter name=iweibomonitor -q)
if [[ -n ${newDockerId} ]]
then
  echo "****************start cat dockerlogs:[${newDockerId}]****************"
  docker logs ${newDockerId}
else
  echo "****************docker run faild:[${newDockerId}]****************"
  exit 100
fi

